<template>
  <!-- 日期时间选择器 -->
  <div
    class="pho-form-item pho-form-flex"
    :style="isTop ? 'flex-direction: column;' : ''"
  >
    <van-field
      class="form-input-hidden"
      v-bind="$attrs"
      :value="formValue.join('')"
      :label="showLabel ? $attrs.label : ''"
      :name="$attrs.__vModel__"
      readonly
      input-align="right"
      label-align="left"
    />
    <div class="right-box form-range-picker" v-if="!isTop">
      <div @click="onClick(0)" class="startPlaceholder">
        <span v-if="formValue[0]">{{ formValue[0] }}</span>
        <span v-else class="van-gray5">{{ $attrs.startPlaceholder }}</span>
      </div>
      <div class="rangeSeparator">{{ $attrs.rangeSeparator }}</div>
      <div @click="onClick(1)" class="endPlaceholder">
        <span v-if="formValue[1]">{{ formValue[1] }}</span>
        <span v-else class="van-gray5">{{ $attrs.endPlaceholder }}</span>
      </div>
    </div>
    <template v-else>
      <van-cell
        class="date-range-cell"
        :class="{ 'form-cell--disabled': $attrs.disabled }"
        :title="$attrs.startPlaceholder"
        :value="formValue[0]"
        is-link
        center
        @click="onClick(0)"
      />
      <van-cell
        class="date-range-cell"
        :class="{ 'form-cell--disabled': $attrs.disabled }"
        :title="$attrs.endPlaceholder"
        :value="formValue[1]"
        is-link
        center
        @click="onClick(1)"
      />
    </template>
    <DatePicker
      ref="DatePicker"
      :type="$attrs.type"
      :format="$attrs.format"
      @callBack="onConfirm"
    />
  </div>
</template>

<script>
import DatePicker from "./components/datePicker.vue";

export default {
  name: "phone-form-daterange-picker",
  components: {
    DatePicker,
  },
  model: {
    prop: "value", // 绑定的值，通过父组件传递
    event: "update",
  },
  props: {
    value: {
      type: [String, Array],
      default: "",
    },
    // 是否展示标题
    showLabel: {
      type: Boolean,
      default: true,
    },
    // 是否为上下布局
    isTop: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      startDate: "", // 开始时间
      endDate: "", // 结束时间
      formValue: ["", ""], // 时间范围
      type: 0, // 0-开始时间 1-结束时间
    };
  },
  watch: {
    value: {
      immediate: true,
      deep: true,
      handler(newValue) {
        this.formValue = newValue || ["", ""];
      },
    },
  },

  methods: {
    // type 0-开始时间 1-结束时间
    onClick(type) {
      this.type = type;
      if (this.$attrs.disabled || this.$attrs.readonly) return;
      this.$refs.DatePicker.open(this.formValue[type]);
    },
    onConfirm(val) {
      this.$set(this.formValue, this.type, val);
      this.$emit("update", this.formValue);
    },
  },
};
</script>

<style lang="scss" scoped></style>
